var gulp = require("gulp"),
    sass = require("gulp-sass"),
    mergeStream = require('merge-stream'),
    htmlmin = require('gulp-htmlmin'),
    stripDebug = require('gulp-strip-debug'),
    uglify = require('gulp-uglify'),
    minfy = require('gulp-minify-css'),
    imagemin = require('gulp-imagemin'),
    runSequence = require('run-sequence'),
    rev = require('gulp-rev'), //生成版本号
    revCollector = require('gulp-rev-collector'), //替换版本号
    clean = require('gulp-clean'), //清空文件夹
    plumber = require('gulp-plumber'),
    browsgulerSync = require('browser-sync'),
    reload = browsgulerSync.reload,
    minimist = require("minimist"),
    gutil = require("gulp-util"),
    changed = require("gulp-changed"),
    debug = require("gulp-debug"),
    through = require('through2'),
    gulpif = require("gulp-if"),
    SourceMap = require('gulp-sourcemaps'),
    // removeUseStrict = require("gulp-remove-use-strict"),
    connect = require('gulp-connect'),
    glob = require('glob'),
    babel = require('gulp-babel'),
    es = require("event-stream"),
    proxyMiddleware = require('http-proxy-middleware'),
    gutil = require('gulp-util'),
    sourcemaps = require('gulp-sourcemaps'),
    buffer = require('vinyl-buffer'),
    globby = require('globby'),
    source = require('vinyl-source-stream'),
    browserify = require('browserify'),
    baseDir = __dirname + "/src"
var api = require('./gulp.config.js');
var localhost = 'https://t.weitao.kr';
//默认development环境

var app = {
    srcPath: 'src/',
    devPath: 'build/'
};

var knowOptions = {
    string: 'env',
    default: {
        env: process.env.NODE_ENV || 'development'
    }
};

var options = minimist(process.argv.slice(2), knowOptions);

//生成filename文件，存入string内容
function string_src(filename, string) {
    var src = require('stream').Readable({
        objectMode: true
    })
    src._read = function () {
        this.push(new gutil.File({
            cwd: "",
            base: "",
            path: filename,
            contents: new Buffer(string)
        }))
        this.push(null)
    }
    return src
};

gulp.task("cleanDist", function () { //打包时清空dist文件夹
    return gulp.src("dist")
        .pipe(clean())
})
if (typeof String.prototype.endswith != 'function') { //判断以什么结尾
    String.prototype.endswith = function (prefix) {
        return this.slice(-prefix.length) === prefix;
    };
}
var condition = function (f) {
    if (f.path.endswith('.min.js')) {
        return false;
    }
    return true;
};
gulp.task("minify", function () { //压缩js,css
    var minCss = gulp.src("src/css/**/*.css")
        // .pipe(changed("dist/css"))
        // .pipe(debug({title: '编译了'}))
        .pipe(minfy())
        .pipe(gulp.dest("dist/css"));
    var minJs = gulp.src(["src/js/**/*.js"])
        .pipe(stripDebug())
        // .pipe(changed("dist/js"))
        // .pipe(debug({title: '编译了'}))
        .pipe(gulpif(condition, babel({
            presets: ['env']
        })))
        .pipe(gulpif(condition, uglify()))
        .pipe(gulp.dest("dist/js"))
    return mergeStream(minCss, minJs)
})

gulp.task('image', function () {
    gulp.src("src/img/*.*")
        .pipe(imagemin({
            progressive: true
        }))
        .pipe(gulp.dest('dist/img'))
})

gulp.task("build_dir", function (cb) {
    return gulp.src([baseDir + "/**", "!" + baseDir + '/**/*.html', "!" + baseDir + "/scss", "!" + baseDir + "/scss/**", "!" + baseDir + "/js", "!" + baseDir + "/js/**", "!" + baseDir + "/css", "!" + baseDir + "/css/**"])
        .pipe(changed("dist"))
        // .pipe(debug({title: '编译了'}))
        .pipe(gulp.dest("dist"))
})

gulp.task("build", function () {
    runSequence('cleanDist', ['constants', 'banben', 'build_dir', 'minify', 'image'])
})
//css文件生成版本号，并将所有的带版本号的文件名统一放入json文件中。
gulp.task('revCSS', function () { //gulp.task--定义一个gulp任务；revCSS--定义该任务的名称，起任何名称都可以
    return gulp.src('src/css/*.css') //gulp.src--指定要操作文件的路径，我的是css文件夹下的所有后缀名为css的文件
        .pipe(rev()) //定义一个流，将所有匹配到的文件名全部生成相应的版本号
        .pipe(rev.manifest()) //把所有生成的带版本号的文件名保存到json文件中
        .pipe(gulp.dest('rev/css')) //把json文件保存到指定的路径，自己记住就好
})
gulp.task('revJs', function () {
    return gulp.src('src/js/**/*.js')
        .pipe(rev())
        .pipe(rev.manifest())
        .pipe(gulp.dest('rev/js'));
})

gulp.task('banben', ['revCSS', 'revJs'], function () { //版本管理
    var options = {
        removeComments: true, //清除HTML注释
        collapseWhitespace: true, //压缩HTML
        collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
        minifyJS: true, //压缩页面JS
        minifyCSS: true //压缩页面CSS
    };
    return gulp.src(['rev/**/*.json', baseDir + '/**/*.html'])
        // .pipe(changed("src/css"))
        // .pipe(debug({title: '编译了'}))
        .pipe(revCollector())
        // .pipe(htmlmin(options))
        // .pipe(gulp.dest(baseDir)); //html更换css,js文件版本，更改完成之后保存的地址
        .pipe(gulp.dest("dist"))
})


gulp.task("buildSass", function () { //编译sass
    return gulp.src('src/scss/*.scss')
        .pipe(changed("src/css"))
        // .pipe(debug({title: '编译了'}))
        .pipe(plumber())
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('src/css'))
        .pipe(reload({
            stream: true
        }))
})

gulp.task('server', ['constants', 'buildSass'], function () { //起一个本地服务
    var middleware = proxyMiddleware(api.api, {
        target: localhost,
        changeOrigin: true
    });
    browsgulerSync({
        server: {
            baseDir: baseDir,
            middleware: middleware,
            // index: "activity/flat_list/index.html"
            // index: "activity/activity_detail/index.html"
            // index: "activity/activity_group/index.html"
        }
    })
    gulp.watch('src/scss/**/*.scss', ['buildSass']);
    gulp.watch(['*.html', '**/*.html', '**/*.js'], {
        cwd: baseDir
    }, reload);
})

// 使用connect启动一个Web服务器
// gulp.task('connect', function () {
//     connect.server({
//         root: baseDir,
//         livereload: true,
//         port: 3000,
//         middleware: function (connect, opt) {
//             return [
//                 proxy('/order', {
//                     target: 'https://t.api.weitao.kr',
//                     // pathRewrite: {'^/order' : '/order'}, // 重写路径
//                     // changeOrigin: true
//                 })
//             ]
//         }
//     });
//     gulp.watch('src/scss/*.scss', ['buildSass']);
//     gulp.watch(['*.html', 'page/**/*.html', 'js/**/*.js'], {
//         cwd: baseDir
//     }, connect.reload);
// });

gulp.task('constants', function () {
    //读入config.json文件
    var myConfig = require('./config.json');
    //取出对应的配置信息
    var envConfig = myConfig[options.env];
    var conConfig = 'var appconfig = ' + JSON.stringify(envConfig);
    //生成config.js文件
    return string_src("config.js", conConfig)
        .pipe(gulp.dest(baseDir + "/js"))
});

// gulp.task('babelJs', function () {
//     return gulp.src(app.srcPath + 'js/**/*.js', {
//             base: app.srcPath
//         })
//         .pipe(plumber())
//         .pipe(babel({　　　　
//             presets: ['env']　　　　　
//         }))
//         .pipe(gulp.dest(app.devPath));
// });